import React, { PureComponent, useState } from 'react';
import { StyleSheet, Text, ToastAndroid, View } from 'react-native';
import { Button, CheckBox, Icon, Overlay } from 'react-native-tengits-elements';
import { TText } from '../../common/Widgets/WidgetDefault';
import _ from 'lodash';
import { OverlayStrategyList } from './StrategyList';
import { Colors, FontSize } from '../../common/Theme/TTheme';
import { scaleSize } from '../../common/Utils/ToolUtils';
import { CircuteCheckItem, LightRadioItem, StrategyRadioItem } from './SubItemComponent';
import { Adjust_Model } from '../../logic/LogicConstant';
import DataCenter from '../../logic/DataCenter';
import Swiper from 'react-native-tengits-swiper';

const CHUNKGROUP = 4;
export default class OverlayBatchBrightness extends PureComponent{
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            checkedLoops: [],
            light: 0,
            adjustModel: Adjust_Model.ADJUST_DIRECT_LIGHT,
            selectStrategy: null,
        };
       this.chunk_data = _.chunk(props.data.loop, CHUNKGROUP);
    }

    setVisible = (v) =>{
        const{strategyList} = this.props;
        if(!strategyList || strategyList.length <= 0) {
            ToastAndroid.show("当前无策略配置", ToastAndroid.SHORT);
        } else {
            this.setState({visible:v});
        }
    }

    setCheckedLoops = (l) => {
        this.setState({checkedLoops: l}, ()=>{
            this.changeDisplay();
        });
    }

    changeDisplay = () => {
        const {data} = this.props;
        const{checkedLoops, light, adjustModel, selectStrategy} = this.state;
        if(checkedLoops.length == 1 ) {
            let temp = data.loop.filter(item=>item.loopNumber == checkedLoops[0])[0];
            if(adjustModel == Adjust_Model.ADJUST_DIRECT_LIGHT && light == 0) {
                this.setLight(temp?.loopCurrentValue || 0);
            } else if(adjustModel == Adjust_Model.ADJUST_STRATEGY_LIGHT && selectStrategy==null){
                this.setSelectStrategy(DataCenter.queryStrategyById(temp.loopStrategyId))
            }
        }
    }

    setLight = (v) => {
        this.setState({light: v});
    }

    setAdjustModel = (v) =>{
        this.setState({adjustModel: v},()=>{
            this.changeDisplay();
        });
    }

    setSelectStrategy = (s) =>{
        this.setState({selectStrategy: s});
    }

    getBtnTitle = () =>{
        const{checkedLoops} = this.state;
        const{data:{loop}} = this.props;
        if(checkedLoops.length == loop.length) {
            return "全不选";
        } else {
            return "全选";
        }
    }

    toggleCheck = (item, loopNumber) => {
        const{checkedLoops} = this.state;
        let filterList = checkedLoops.filter(item => item !== loopNumber);
        if(filterList.length != checkedLoops.length) {
            this.setCheckedLoops([...filterList]);
        } else {
            this.setCheckedLoops([...filterList, loopNumber]);
        }
    }

    sliderCallbackWrap = (value) => {
        const{checkedLoops} = this.state;
        const{data, sliderCallback} = this.props;
        this.setLight(value);
        sliderCallback && sliderCallback(data, checkedLoops, value);
    }

    sliderCompleteCallbackWrap = (value) => {
        const{checkedLoops} = this.state;
        const{data, sliderCompleteCallback} = this.props;
        this.setLight(value);
        sliderCompleteCallback && sliderCompleteCallback(data, checkedLoops, value);
    }
    
    toggleStrategyOverlay = () => {
        this.setVisible(false);
    }

    onSelectStrategySure = (key, s) => {
        this.setSelectStrategy(s);
        this.setVisible(false);
    }

    render() {
        const {data, strategyList, toggleOverlay, onSure} = this.props;
        const{visible, checkedLoops, light, adjustModel, selectStrategy} = this.state;
        return (
            <View style={{flex:1, flexDirection:'column', backgroundColor:Colors.white}}>
                <View style={styles.header}>
                    <Text style={{fontSize: FontSize.h3_font, color: Colors.white}}>{"高级调光"}</Text>
                    <Button 
                        containerStyle={{position:'absolute', top:0, right:0}}
                        buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                        icon={<Icon name='close' color={Colors.white} size={scaleSize(40)}/>}
                        onPress={()=>{
                            toggleOverlay && toggleOverlay("BatchBrightness");
                    }}/>
                </View>
                <View style={{flex:1, paddingVertical:scaleSize(30)}}>
                    {this.chunk_data.length > 0 ? <Swiper index={0} showsButtons={true} 
                            loop={false} autoplay={false} buttonWrapperStyle={{paddingHorizontal:0}}
                            prevButton={<Icon size={scaleSize(40)} name='chevron-left' type='font-awesome' containerStyle={styles.pageBtn} color={Colors.button_color}/>}
                            nextButton={<Icon size={scaleSize(40)} name='chevron-right' type='font-awesome' containerStyle={styles.pageBtn} color={Colors.button_color}/>}
                            showsPagination={false} scrollEnabled={false}>
                        {this.chunk_data.map((item, ix)=>{
                            return <View key={"cc1_" + ix} style={{flex:1, paddingHorizontal:scaleSize(98), flexDirection:'row', flexWrap:'wrap', justifyContent:'space-between'}}>
                                {item.map((it, i)=>{
                                    return <CircuteCheckItem 
                                        key={"cc_" + i}
                                        item={it}
                                        index={it.loopNumber} 
                                        checkedIndex={checkedLoops}
                                        callback={this.toggleCheck}/>
                                })}
                            </View>
                        })}    
                    </Swiper> : null}
                    <View style={{flex:1, paddingHorizontal:scaleSize(98), flexDirection:'column'}}>
                        <LightRadioItem light={light} 
                            checkedIndex={adjustModel}
                            disabled={adjustModel != Adjust_Model.ADJUST_DIRECT_LIGHT}
                            index={Adjust_Model.ADJUST_DIRECT_LIGHT} 
                            callback={()=>{this.setAdjustModel(Adjust_Model.ADJUST_DIRECT_LIGHT)}}
                            sliderCallback={this.sliderCallbackWrap}
                            sliderCompleteCallback={this.sliderCompleteCallbackWrap}
                            />
                        <StrategyRadioItem 
                            checkedIndex={adjustModel} 
                            index={Adjust_Model.ADJUST_STRATEGY_LIGHT} 
                            name={selectStrategy?.name}
                            callback={()=>{this.setAdjustModel(Adjust_Model.ADJUST_STRATEGY_LIGHT)}}
                            btnCallback={()=>{this.setVisible(true)}}
                            />
                    </View>
                    <View style={{flexDirection:'row', justifyContent:'center'}}>
                        <Button buttonStyle={{paddingVertical:0, width:scaleSize(286), height:scaleSize(62), backgroundColor: Colors.second_button_color}} 
                            titleStyle={{color:Colors.text1_color, fontSize:FontSize.h4_font}}
                            title={this.getBtnTitle()}
                            onPress={()=>{
                                if(checkedLoops.length != data.loop.length) {
                                    let ret = data.loop.map(item=>item.loopNumber);
                                    this.setCheckedLoops(ret);
                                } else {
                                    this.setCheckedLoops([]);
                                }
                        }}/>
                        <Button buttonStyle={{paddingVertical:0, marginLeft:scaleSize(30), width:scaleSize(286), height:scaleSize(62), backgroundColor: Colors.second_button_color}} 
                            titleStyle={{color:Colors.text1_color, fontSize:FontSize.h4_font}}
                            title={"取消"}
                            onPress={()=>{
                            toggleOverlay && toggleOverlay("BatchBrightness");
                        }}/>
                        <Button buttonStyle={{paddingVertical:0, marginLeft:scaleSize(30), width:scaleSize(286), height:scaleSize(62), backgroundColor:Colors.button_color}} 
                            titleStyle={{fontSize: FontSize.h4_font}}
                            title={"提交"} onPress={async()=>{
                            if(checkedLoops.length <= 0){
                                ToastAndroid.show("请先选择回路", ToastAndroid.SHORT);
                                return;
                            }
                            if(adjustModel == 0) {
                                ToastAndroid.show("请先选择调光模式", ToastAndroid.SHORT);
                                return;
                            }
                            if(adjustModel == Adjust_Model.ADJUST_STRATEGY_LIGHT && !selectStrategy) {
                                ToastAndroid.show("请先选择调光策略", ToastAndroid.SHORT);
                                return;
                            }
                            onSure && onSure("BatchBrightness",{loops: checkedLoops, light: light, model:adjustModel, strategy: selectStrategy});
                        }}/>
                    </View>
                </View>
                <Overlay overlayStyle={{padding:0}} isVisible={visible} onBackdropPress={this.toggleStrategyOverlay} fullScreen>
                    <OverlayStrategyList data={strategyList} canSel={true}
                        id={selectStrategy?.id}
                        toggleOverlay={this.toggleStrategyOverlay}
                        onSure={this.onSelectStrategySure}/>
                </Overlay>
            </View>
      );
    }
};

const styles = StyleSheet.create({
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
        alignItems:'center',
        justifyContent:'center'
    },
    pageBtn:{
        justifyContent:'center',
        width:scaleSize(100), 
        height:scaleSize(200),
    }
});